<template>
  <el-dialog draggable :title="title" v-model="dialogVisible" width="60%" :before-close="handleClose"
    :close-on-click-modal="false" 
    >
    <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
      <!-- 供应商名称 -->
      <el-form-item label="供应商名称" prop="name">
        <el-input v-model="formData.name" :disabled="!isEditMode" placeholder="请输入供应商名称" />
      </el-form-item>

      <!-- 联系人 -->
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" :disabled="!isEditMode" placeholder="请输入联系人" />
      </el-form-item>

      <!-- 联系电话 -->
      <el-form-item label="联系电话" prop="contactPhoneNumber">
        <el-input v-model="formData.contactPhoneNumber" :disabled="!isEditMode" placeholder="请输入联系电话"  type="number"/>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" :disabled="!isEditMode" placeholder="请输入邮箱" />
      </el-form-item>

      <!-- 城市 -->
      <el-form-item label="城市" prop="city">
        <el-input v-model="formData.city" :disabled="!isEditMode" placeholder="请输入城市" />
      </el-form-item>

      <!-- 地址 -->
      <el-form-item label="地址" prop="address">
        <el-input v-model="formData.address" :disabled="!isEditMode" placeholder="请输入地址" />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" :disabled="!isEditMode" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </el-form-item>

      <!-- 启用状态 -->
      <el-form-item label="启用状态" prop="enabled">
        <el-switch v-model="formData.enabled" :disabled="!isEditMode" active-text="启用" inactive-text="停用" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">{{ cancelText }}</el-button>
      <el-button v-if="isEditMode" type="primary" @click="handleSubmit" :loading="loading">
        {{ confirmText }}
      </el-button>
      <el-button v-if="showDelete && !isEditMode && supplier.id" type="danger" @click="handleDelete" :loading="loading">
        删除
      </el-button>
      <el-button v-if="showEdit && !isEditMode" type="primary" @click="toggleEditMode(true)">
        编辑
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { Supplier } from '../../public/engine/targetOrg/supplier'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateOrCreateSupplier, removeSupplier } from '../../public/network/api'

export default {
  name: 'SupplierBasicInfoDialog',
  props: {
    visible: {
      type: Boolean,
      required: true,
      default: true
    },

    mode: {
      type: String,
      default: 'view', // 'view' | 'edit' | 'create'
      validator: val => ['view', 'edit', 'create'].includes(val)
    },
    showEdit: {
      type: Boolean,
      default: true
    },
    showDelete: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '供应商信息'
    },
    confirmText: {
      type: String,
      default: '保存'
    },
    cancelText: {
      type: String,
      default: '取消'
    }
  },
  data() {
    return {
      supplier: new Supplier(),
      formData: {
        name: '',
        contactName: '',
        contactPhoneNumber: '',
        email: '',
        city: '',
        address: '',
        remark: '',
        enabled: true
      },
      rules: {
        name: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        contactPhoneNumber: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      loading: false,

      dialogVisible: false,
    }
  },
  computed: {
    isEditMode() {
      return this.mode === 'edit' || this.mode === 'create'
    }
  },

  methods: {

    open(supplierData) {
      console.log('open supplier basic info dialog', supplierData)
      this.dialogVisible = true
      this.supplier = Supplier.clone(supplierData) || Supplier.empty();
      this.initFormData() // 确保每次打开都初始化数据
    },
    initFormData() {      
      this.syncFormData()
    },
    syncFormData() {
      this.formData = {
        name: this.supplier.name || '',
        contactName: this.supplier.contactName || '',
        contactPhoneNumber: this.supplier.contactPhoneNumber || '',
        email: this.supplier.email || '',
        city: this.supplier.city || '',
        address: this.supplier.address || '',
        remark: this.supplier.remark || '',
        enabled: this.supplier.enabled ?? true
      }
    },
    fillWithFormData() {
      Object.assign(this.supplier, {
        name: this.formData.name,
        contactName: this.formData.contactName,
        contactPhoneNumber: this.formData.contactPhoneNumber,
        email: this.formData.email,
        city: this.formData.city,
        address: this.formData.address,
        remark: this.formData.remark,
        enabled: this.formData.enabled
      })
    },
    toggleEditMode(edit) {
      this.$emit('update:mode', edit ? 'edit' : 'view')
    },
    handleClose() {
      this.dialogVisible = false;
      //this.$emit('update:visible', false)
    },
    handleCancel() {     
        this.handleClose()      
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.fillWithFormData()

        this.loading = true
        const res = await updateOrCreateSupplier(this.supplier)

        if (res?.data) {
          ElMessage.success(this.mode === 'create' ? '创建成功' : '更新成功')
          this.$emit('submit', {
            type: this.mode === 'create' ? 'create' : 'update',
            data: this.supplier
          })
          this.handleClose()
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        this.loading = false
      }
    },
    async handleDelete() {
      try {
        await ElMessageBox.confirm('确定删除该供应商吗？', '提示', {
          type: 'warning'
        })

        this.loading = true
        const res = await removeSupplier(this.supplier.id)

        if (res?.data) {
          ElMessage.success('删除成功')
          this.$emit('submit', {
            type: 'delete',
            data: this.supplier.id
          })
          this.handleClose()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>